<template>
  <div class="pagination">
    <!--当前页码为1，不可操作-->
    <button :disabled="pageNo===1" @click="$emit('change-page',pageNo-1)">上一页</button>
    <button v-if="startEnd[0]>1" @click="$emit('change-page',1)">1</button>
    <button disabled v-if="pageNo>2">···</button>

    <button v-for="item in startEnd" :key="item" :class="{active:pageNo===item}"
            @click="$emit('change-page',item)">
      {{ item }}
    </button>

    <button disabled v-if="startEnd[startEnd.length-1]<totalPages-1">···</button>
    <button v-if="startEnd[startEnd.length-1]<totalPages"
            @click="$emit('change-page',totalPages)">
      {{ totalPages }}
    </button>
    <!--当前页码为最大页码，不可操作-->
    <button :disabled="pageNo===totalPages" @click="$emit('change-page',pageNo+1)">下一页</button>
    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>

</template>
<script setup lang="ts" name="Pagination">
import {computed} from "vue";

const props = withDefaults(defineProps<{
  total: number,//总条数
  showPageNo?: number,//连续页码数
  pageSize?: number,//每页数量
  pageNo?: number,//当前页码
  totalPages: number//总页数
}>(), {
  showPageNo: 5,
  pageSize: 10,
  pageNo: 1,
})

/**
 * 计算连续页码的起始和结束
 */
const startEnd = computed(() => {
  let {showPageNo, pageNo, totalPages} = props;
  //计算start
  let start = pageNo - Math.floor(showPageNo / 2);
  //start最小是1，进行修正
  start < 1 && (start = 1);

  //计算end
  let end = start + showPageNo - 1;
  //end最大是总页数，进行修正
  if (end > totalPages) {
    end = totalPages;
    start = end - showPageNo + 1;
    start < 1 && (start = 1);
  }
  return Array.from({length: (end - start) + 1}, (_, i) => start + i);
})
</script>
<style scoped lang="less">

.pagination {
  text-align: center;

  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
